import { removeToken } from './../../utils/token'
import { ApiRes, LoginForm, Token } from '@/types/data'
import { LoginAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { setToken } from '@/utils/token'

export function login(values: LoginForm): RootThunkAction {
  return async (dispatch) => {
    const res = await request.post<ApiRes<Token>>('/authorizations', values)

    const token = res.data.data
    dispatch({
      type: 'login/login',
      payload: token
    })

    setToken(token)
  }
}

export function sendCode(mobile: string): RootThunkAction {
  return async (dispatch) => {
    await request.get(`/sms/codes/${mobile}`)
  }
}

export function logout(): LoginAction {
  removeToken()

  return {
    type: 'login/logout'
  }
}
